package com.tuling.jucdemo.lock;

import com.tuling.jucdemo.threadbase.ThreadStopDemo2;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :tangweiliang
 * @date : 2022/11/17 23:02
 * 未来的你会感谢现在努力的自己
 * <p>
 * 条件变量
 */
@Slf4j
public class ReentrantLockDemo6 {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition cigCon = lock.newCondition();
    private static Condition takeCon = lock.newCondition();

    private static boolean hashcig = false;
    private static boolean hastakeout = false;

    //送烟
    public void cigratee() {
        lock.lock();
        try {
            while (!hashcig) {
                log.debug("没有烟,休息一会");
                try {
                    cigCon.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("有烟了,干活");
        } finally {
            lock.unlock();
        }
    }

    //送外卖
    public void takeOut(){
        lock.lock();
        try{
            while (!hastakeout){
                log.debug("没有饭,休息一会");
                try {
                    takeCon.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("有饭了,干活");
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo6 test = new ReentrantLockDemo6();

        new Thread(()->{
            test.cigratee();
        }).start();

        new Thread(()->{
           test.takeOut();
        }).start();

        //唤醒送烟的线程
        new Thread(()->{
           lock.lock();
           try{
               hashcig = true;
               log.debug("唤醒送烟的等待线程");
               cigCon.signal();
           }finally {
               lock.unlock();
           }
        },"t1").start();

        //唤醒送外卖的等待线程
        new Thread(()->{
            lock.lock();
            try {
                hastakeout = true;
                log.debug("唤醒送外卖的等待线程");
                takeCon.signal();
            } finally { // ctrl + alt + t
                lock.unlock();
            }
        },"t2").start();
    }
}
